package com.ty.mianshiya.job.cycle;

import cn.hutool.core.collection.CollUtil;
import com.ty.mianshiya.annotation.DistributedLock;
import com.ty.mianshiya.mapper.QuestionEsDao;
import com.ty.mianshiya.mapper.QuestionMapper;
import com.ty.mianshiya.model.dto.question.QuestionEsDTO;
import com.ty.mianshiya.model.entity.Question;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class IncSyncQuestionToEs {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionEsDao questionEsDao;

    /**
     * 每分钟执行一次
     */
    @Scheduled(fixedRate = 60*1000)
    @DistributedLock(key = "incSyncQuestionToEsLock",leaseTime = 20000,waitTime = 5000)
    public void  run(){
        //查询进5分钟数据
        long FIVE_MINUTES=5*60*1000L;
        Date fiveMinutesAgoDate = new Date(new Date().getTime() - FIVE_MINUTES);
        List<Question> questionList = questionMapper.listQuestionWithDelete(fiveMinutesAgoDate);
        if(CollUtil.isEmpty(questionList)){
            log.info("no inc question");
            return;
        }
        List<QuestionEsDTO> questionEsDTOList = questionList.stream().map(QuestionEsDTO::objToDto).collect(Collectors.toList());
        int total = questionEsDTOList.size();
        log.info("IncSyncQuestionToEs start, total {}", total);
        final int pageSize=500;
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            questionEsDao.saveAll(questionEsDTOList.subList(i, end));
        }
        log.info("IncSyncQuestionToEs end, total {}", total);
    }
}
